package com.volunteer.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.volunteer.common.R;
import com.volunteer.entity.Activity;
import com.volunteer.entity.Registration;
import com.volunteer.service.RegistrationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 活动报名控制器
 */
@Tag(name = "活动报名管理")
@Slf4j
@RestController
@RequestMapping("/registration")
@RequiredArgsConstructor
public class RegistrationController {

    private final RegistrationService registrationService;

    /**
     * 用户报名活动
     */
    @Operation(summary = "用户报名活动")
    @PostMapping("/register/{activityId}")
    public R<Boolean> register(@Parameter(description = "活动ID") @PathVariable Long activityId) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean result = registrationService.register(activityId, userId);
        return R.ok(result);
    }

    /**
     * 取消报名
     */
    @Operation(summary = "取消报名")
    @PostMapping("/cancel/{registrationId}")
    public R<Boolean> cancelRegistration(
            @Parameter(description = "报名ID") @PathVariable Long registrationId
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean result = registrationService.cancelRegistration(registrationId, userId);
        return R.ok(result);
    }

    /**
     * 审核报名
     */
    @Operation(summary = "审核报名")
    @PostMapping("/audit/{registrationId}/{status}")
    @SaCheckRole(value = {"admin", "leader"}, mode = SaMode.OR)
    public R<Boolean> auditRegistration(
            @Parameter(description = "报名ID") @PathVariable Long registrationId,
            @Parameter(description = "状态：1-通过，2-拒绝") @PathVariable Integer status,
            @Parameter(description = "备注") @RequestParam(required = false) String remark
    ) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        boolean result = registrationService.auditRegistration(registrationId, status, remark, operatorId);
        return R.ok(result);
    }

    /**
     * 签到
     */
    @Operation(summary = "签到")
    @PostMapping("/check-in/{registrationId}")
    @SaCheckRole(value = {"admin", "leader"},mode = SaMode.OR)
    public R<Boolean> checkIn(
            @Parameter(description = "报名ID") @PathVariable Long registrationId
    ) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        boolean result = registrationService.checkIn(registrationId, operatorId);
        return R.ok(result);
    }

    /**
     * 查询活动报名列表
     */
    @Operation(summary = "查询活动报名列表")
    @GetMapping("/activity/{activityId}")
    @SaCheckRole(value = {"admin", "leader"}, mode = SaMode.OR)
    public R<Page<Registration>> pageActivityRegistrations(
            @Parameter(description = "活动ID") @PathVariable Long activityId,
            @Parameter(description = "状态：0-待审核，1-已通过，2-已拒绝，3-已签到") @RequestParam(required = false) Integer status,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") long current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") long size
    ) {
        Page<Registration> page = new Page<>(current, size);
        Page<Registration> result = registrationService.pageActivityRegistrations(page, activityId, status);
        return R.ok(result);
    }

    /**
     * 查询用户报名列表
     */
    @Operation(summary = "查询用户报名列表")
    @GetMapping("/user")
    public R<Page<Registration>> pageUserRegistrations(
            @Parameter(description = "状态：0-待审核，1-已通过，2-已拒绝，3-已签到") @RequestParam(required = false) Integer status,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") long current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") long size
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        Page<Registration> page = new Page<>(current, size);
        Page<Registration> result = registrationService.pageUserRegistrations(page, userId, status);
        return R.ok(result);
    }

    /**
     * 检查用户是否报名活动
     */
    @Operation(summary = "检查用户是否报名活动")
    @GetMapping("/check/{activityId}")
    public R<Boolean> isUserRegistered(
            @Parameter(description = "活动ID") @PathVariable Long activityId
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean result = registrationService.isUserRegistered(activityId, userId);
        return R.ok(result);
    }

    /**
     * 获取用户报名信息
     */
    @Operation(summary = "获取用户报名信息")
    @GetMapping("/info/{activityId}")
    public R<Registration> getUserRegistration(
            @Parameter(description = "活动ID") @PathVariable Long activityId
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        Registration registration = registrationService.getUserRegistration(activityId, userId);
        return R.ok(registration);
    }

    /**
     * 获取用户已报名的活动列表
     */
    @GetMapping("/registered-activities/{userId}")
    public R<List<Activity>> getRegisteredActivities(@PathVariable Long userId) {
        // 假设Register表有userId和activityId字段
        List<Activity> activities = registrationService.getRegisteredActivitiesByUserId(userId);
        return R.ok(activities);
    }

    /**
     * 用户自助签到
     */
    @Operation(summary = "用户自助签到")
    @PostMapping("/user-check-in/{registrationId}")
    public R<Boolean> userCheckIn(
            @Parameter(description = "报名ID") @PathVariable Long registrationId
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean result = registrationService.userCheckIn(registrationId, userId);
        return R.ok(result);
    }
    
    /**
     * 获取用户所有报名记录（包含更多信息）
     */
    @Operation(summary = "获取用户所有报名记录")
    @GetMapping("/user/list")
    public R<Page<Registration>> getUserRegistrationList(
            @Parameter(description = "状态：0-待审核，1-已通过，2-已拒绝，3-已取消") @RequestParam(required = false) Integer status,
            @Parameter(description = "活动标题") @RequestParam(required = false) String title,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") long current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") long size
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        Page<Registration> page = new Page<>(current, size);
        Page<Registration> result = registrationService.getUserRegistrationListWithDetail(page, userId, status, title);
        return R.ok(result);
    }
}
